package org.benjamin.lending.trusteeship.sumapay;

import org.benjamin.lending.domain.entity.*;
import org.benjamin.lending.repository.BorrowInfoRepository;
import org.benjamin.lending.repository.MemberInfoRepository;
import org.benjamin.lending.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>丰付投标操作</p>
 * @author 黄文杰
 */
@Component("sumapayTenderOperation")
public class TenderOperation extends SumapayAbstractOperation {

    @Autowired
    private BorrowService borrowService;

    @Autowired
    private BorrowInfoRepository borrowInfoRepository;

    @Autowired
    private MemberInfoRepository memberInfoRepository;


    @Override
    protected void processRequest(Map<String, Object> requestMap, MemberInfo memberInfo, BorrowInfo borrowInfo, Map<String, Object> parameterMap) {
        Assert.isTrue(memberInfo.getMemberStatus().isOpenAccount(),"您为在丰付存管进行开户！");
        BigDecimal amount = new BigDecimal(parameterMap.get("amount").toString());
        requestMap.put("sum",amount);
        requestMap.put("projectCode",borrowInfo.getNo());
        requestMap.put("projectSum",borrowInfo.getTotalMoney());
    }

    @Override
    protected String signatureRequest(Map<String, Object> requestMap) {
        String[] keys = {"requestId","merchantCode","userIdIdentity","sum","projectCode","projectDescription",
        "successReturnUrl","failReturnUrl","noticeUrl"};
        String[] temp = this.buildSignature(requestMap,keys);
        requestMap.put(this.SIGNATURE,temp[1]);
        return temp[0];
    }

    @Override
    protected void afterRequest(Map<String, Object> parameterMap, MemberInfo memberInfo,BorrowInfo borrowInfo, TrusteeshipRequest trusteeshipRequest) {
        trusteeshipRequest.setType(TrusteeshipType.tender);
        this.abutmentUrl = sumaplayConfig.getServiceName()+"/user/manualBid_toManualBid";
    }

    @Override
    protected void processResponse(TrusteeshipRequest trusteeshipRequest, Map<String, Object> responseMap) throws RuntimeException {
        BorrowInfo borrowInfo = this.borrowInfoRepository.findOne(trusteeshipRequest.getBid());
        MemberInfo memberInfo = this.memberInfoRepository.findOne(trusteeshipRequest.getUid());
        BigDecimal amount = new BigDecimal(responseMap.get("sum").toString());
        BorrowTender borrowTender =this.borrowService.tenderSuccess(borrowInfo,memberInfo,amount,false);
        trusteeshipRequest.setRel(borrowTender.getId());
        super.processResponse(trusteeshipRequest, responseMap);
    }

    @Override
    protected String[] signatureResponse(Map<String, Object> responseMap) {
        return this.buildSignature(responseMap,"requestId","result","sum","userIdIdentity");
    }
}
